package cn.cvs.controller;

import cn.cvs.pojo.SysRole;
import cn.cvs.pojo.SysUser;
import cn.cvs.service.SysRoleService;
import cn.cvs.service.SysUserService;
import cn.cvs.utils.PageSupport;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.mysql.jdbc.StringUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.math.RandomUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/sys/user")
public class SysUserController {
    @Resource
    private SysRoleService sysRoleService;
    @Resource
    private SysUserService sysUserService;

    @RequestMapping("/list")
    public String getSysUserList(Model model, @RequestParam(required = false) String queryRealName, @RequestParam(required = false) Integer queryRoleId, @RequestParam(defaultValue = "1", required = false) Integer pageIndex) {

        //查询所有角色
        List<SysRole> roleList = sysRoleService.getRoleList();
        //查询用户数量
        int pageCounts = sysUserService.getCountByNameAndRoleId(queryRealName, queryRoleId);
        //用户每页显示数量
        int pageSize = 5;
        //总页数
        PageSupport p = new PageSupport();
        p.setCurrentPageNo(pageIndex);
        p.setPageSize(pageSize);
        p.setTotalCount(pageCounts);
        int totalPageCount = p.getTotalPageCount();
        //控制首页和尾页
        if (pageIndex > totalPageCount) {
            pageIndex = totalPageCount;
            throw new RuntimeException("页码不正确");
        }

        List<SysUser> userList = sysUserService.getUserByNameAndRoleId(queryRealName, queryRoleId, pageIndex, pageSize);
        //存储用户集合
        model.addAttribute("userList", userList);
        //存储角色集合
        model.addAttribute("roleList", roleList);
        //查询的用户名
        model.addAttribute("queryRealName", queryRealName);
        //查询的角色id
        model.addAttribute("queryRoleId", queryRoleId);
        //总页数
        model.addAttribute("totalPageCount", totalPageCount);
        //查询总数量
        model.addAttribute("totalCount", pageCounts);
        //当前页码
        model.addAttribute("currentPageNo", pageIndex);

        return "sysUser/list";
    }

    @RequestMapping("/toAdd")
    public String toAdd() {
        return "sysUser/add";
    }

    @RequestMapping("/add")
    public String add(SysUser sysUser, HttpSession session, MultipartFile[] attachs, Model model) {

        String idPicPath = "";
        String workPicPath = "";
        String errorInfo = "";

        //定义文件存储路径
        String path = session.getServletContext().getRealPath("statics" + File.separator + "upload");
        for (int i = 0; i < attachs.length; i++) {
            System.out.println("进入文件上传");
            MultipartFile pic = attachs[i];
            //判断是否为空
            if (!pic.isEmpty()) {
                if (i == 0) {
                    errorInfo = "uploadFileError";
                } else if (i == 1) {
                    errorInfo = "uploadWpError";
                }
                //获取原文件名
                String oldFileName = pic.getOriginalFilename();
                //获取原文件后缀
                String suffix = FilenameUtils.getExtension(oldFileName);
                //设置文件上传大小
                int fileSize = 500000;
                //判断文件大小
                if (pic.getSize() > fileSize) {
                    model.addAttribute(errorInfo, "上传大小不得超过500KB");
                    System.out.println("上传太大");
                    return "sysUser/add";
                    //判断文件格式
                } else if (suffix.equalsIgnoreCase("jpg") ||
                        suffix.equalsIgnoreCase("png") ||
                        suffix.equalsIgnoreCase("jpeg") ||
                        suffix.equalsIgnoreCase("pneg")) {

                    //给文件重命名
                    String newFileName = System.currentTimeMillis() + RandomUtils.nextInt(1000000) + "." + suffix;
                    File file = new File(path);
                    if (!file.exists()) {
                        file.mkdirs();
                    }
                    //保存
                    try {
                        pic.transferTo(new File(file, newFileName));
                        System.out.println("上传成功！");
                    } catch (IOException e) {
                        e.printStackTrace();
                        model.addAttribute(errorInfo, "上传失败");
                        System.out.println("上传失败");
                        return "sysUser/add";
                    }
                    //存储文件路径
                    if (i == 0) {
                        idPicPath = File.separator + "statics" + File.separator + "upload" + File.separator + newFileName;
                    } else if (i == 1) {
                        workPicPath = File.separator + "statics" + File.separator + "upload" + File.separator + newFileName;
                    }
                    System.out.println("idpicpath" + idPicPath);
                    System.out.println("workpicpath" + workPicPath);

                } else {
                    model.addAttribute(errorInfo, "上传文件格式不正确");
                    System.out.println("上传文件格式不正确");
                    return "sysUser/add";
                }

            }
        }
        System.out.println("idpicpath" + idPicPath);
        System.out.println("workpicpath" + workPicPath);
        SysUser user = (SysUser) session.getAttribute("userSession");
        sysUser.setCreatedUserId(user.getId());
        sysUser.setCreatedTime(new Date());
        sysUser.setIdPicPath(idPicPath);
        sysUser.setWorkPicPath(workPicPath);
        int num = sysUserService.addUser(sysUser);
        if (num > 0) {
            return "redirect:/sys/user/list";
        }
        return "sysUser/add";
    }

    @ResponseBody
    @GetMapping(value = "/view/{userid}")
    public Object view(@PathVariable Integer userid) {
        // String json="";
       /* if(userid==null||userid.equals("")){
            return "nodata" ;
        }else{*/
        SysUser sysUser = null;
        try {
            sysUser = sysUserService.getUserById(userid);
            // json=JSON.toJSONString(sysUser);
        } catch (Exception e) {
            e.printStackTrace();
            return "failed";
        }
        // return json;
        // }
        return sysUser;
    }


    @GetMapping("/toUpdate")
    public String toUpdate(Integer uid, Model model) {
        SysUser sysUser = sysUserService.getUserById(uid);
        model.addAttribute("sysUser", sysUser);
        //System.out.println("1111uuuuuuuu");
        return "sysUser/update";
    }


    @PostMapping("/update")
    public String update(SysUser sysUser, HttpSession session) {
        SysUser user = (SysUser) session.getAttribute("userSession");
        sysUser.setUpdatedUserId(user.getId());
        sysUser.setUpdatedTime(new Date());
        int num = sysUserService.updUser(sysUser);
        if (num > 0) {
            return "redirect:/sys/user/list";
        }
        return "sysUser/update";
    }

    @RequestMapping("/toUpdatePwd")
    public String toUpdatePwd() {
        return "sysUser/updatePassword";
    }

    @ResponseBody
    @PostMapping("/checkOldPwd")
    public Object updatePassword(HttpSession session, String oldPassword) {
        System.out.println("密码验证");
        Map<String, Object> map = new HashMap<>();
        //先判断会话是否过期
        if (null == session.getAttribute("userSession")) {
            map.put("result", "sessionerror");
        } else if (StringUtils.isNullOrEmpty(oldPassword)) {
            map.put("result", "error");
        } else {
            SysUser sysUser = (SysUser) session.getAttribute("userSession");
            if (sysUser.getPassword().equals(oldPassword)) {
                map.put("result", "true");
            } else {
                map.put("result", "false");
            }
        }
        return JSONArray.toJSONString(map);
    }


    @PostMapping("/savePassword")
    public String savePassword(HttpSession session, String newPassword, Model model) {
        SysUser sysUser = (SysUser) session.getAttribute("userSession");
        if (sysUser != null && !StringUtils.isNullOrEmpty(newPassword)) {
            int num = sysUserService.updLoginPwd(newPassword, sysUser.getId());
            if (num > 0) {
                model.addAttribute("message", "修改密码成功,请退出并重新登录！");
                session.removeAttribute("userSession");
                return "login";
            } else {
                model.addAttribute("message", "修改密码失败！");
            }
        } else {
            model.addAttribute("message", "修改密码失败！");
        }

        return "sysUser/updatePassword";
    }

    //验证账号同名
    @GetMapping("/userExist")
    @ResponseBody
    public Object userExist(String account) {
        System.out.println("同名验证");
        Map<String, Object> map = new HashMap<>();
        List<SysUser> user = null;
        try {
            user = sysUserService.getUserByName(account);
            System.out.println("tongming===:" + user);
            if (user.size() > 0) {
                map.put("exist", 1);
            } else {
                map.put("exist", 0);
            }
        } catch (Exception e) {
            e.printStackTrace();
            map.put("exist", -1);
        }
        return JSON.toJSONString(map);
    }


    //删除用户
    @ResponseBody
    @RequestMapping("/delUser")
    public Object delUser(Integer uid){
        //System.out.println("del-====:"+uid);
        Map<String,Object> map=new HashMap<>();
        int a=-1;
        try {
            a=sysUserService.delUser(uid);
            if(a>0){
                map.put("delResult","true");
            }else {
                map.put("delResult","false");
            }
        } catch (Exception e) {
            e.printStackTrace();
            map.put("delResult","notexist");
        }
        return map;
    }


}
